package ro.sep.web;

import java.util.List;

import javax.faces.bean.ViewScoped;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ro.sep.web.services.ISearchEngine;
import ro.sep.web.services.model.SearchSiteResult;

@Component
@ViewScoped
public class SearchBean {

	private static final Integer PAGE_SIZE = 2;
	public static final String RESULT_PAGE = "result.jsf";
	private String searchText;
	private List<SearchSiteResult> searchResult;
	private Integer pageNumber = 1;
	
	@Autowired
	private ISearchEngine searchEngine;
	
	public void setSearchEngine(ISearchEngine searchEngine) {
		this.searchEngine = searchEngine;
	}

	public String getSearchText() {
		return searchText;
	}
	
	public void setSearchText(String searchText) {
		this.searchText = searchText;
	}
	
	public List<SearchSiteResult> getSearchResult() {
		return searchResult;
	}
	
	public void setSearchResult(List<SearchSiteResult> searchResult) {
		this.searchResult = searchResult;
	}
	
	public Integer getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(Integer pageNumber) {
		this.pageNumber = pageNumber;
	}

	public String search() {
		return RESULT_PAGE + "?faces-redirect=true";
	}
	
	public List<SearchSiteResult> getResults() {
		if (searchText != null && !"".equals(searchText)) {
			if (searchResult == null) {
				searchResult = searchEngine.search(searchText);
			}
		}
		return searchResult;
	}

	public Integer getPageSize() {
		Integer pageSize;
		if (pageNumber > 1) {
			pageSize = pageNumber * PAGE_SIZE;
		} else {
			pageSize = PAGE_SIZE;
		}
		if (pageSize > searchResult.size()) {
			pageSize = searchResult.size();
		}
		return pageSize;
	}
	
	public Integer getNumberOfPages() {
		Integer numberOfPages = searchResult.size() / PAGE_SIZE;
		if (searchResult.size() % PAGE_SIZE > 0) {
			numberOfPages++;
		}
		return numberOfPages;
	}
	
	public String lastPage() {
		pageNumber = getNumberOfPages();
		return RESULT_PAGE;
	}
	
	public String firstPage() {
		pageNumber = 1;
		return RESULT_PAGE;
	}
	
	public String nextPage() {
		pageNumber++;
		return RESULT_PAGE;
	}
	
	public String previousPage() {
		pageNumber--;
		return RESULT_PAGE;
	}
	
	public boolean isLastPage() {
		return (pageNumber >= getNumberOfPages());
	}
	
	public boolean isFirstPage() {
		return (pageNumber <= 1);
	}
	
	public Integer getPageOffset() {
		return (pageNumber - 1) * PAGE_SIZE;
	}
}